<script lang="ts" setup>
import { ref } from 'vue'
import { toNumber } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { GetData } from '@/api/modules/drawactuser'
import { GetOptionData, PostSendDrawChance } from '@/api/modules/drawact'

// const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()

const findFrom = ref({
  DrawId: '',
  UserId: '',
  SCOpenId: '',
  UserPhone: '',
  OrderNo: '',
})
const dataList: any = reactive({
  list: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20
let PageNum = toNumber(localStorage.getItem('currentPage')) || 1

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.DrawId && ({ DrawId: findFrom.value.DrawId })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.SCOpenId && ({ SCOpenId: findFrom.value.SCOpenId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.OrderNo && ({ OrderNo: findFrom.value.OrderNo })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 查看明细
function ViewDetails(UserId: number, drawId: number) {
  if (!UserId) {
    ElMessage.error('用户未授权')
    return 0
  }

  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'drawactuserDetail',
    query: {
      UserId,
      drawId,
    },
  })
}

function GetDrawactRecord(UserId: number, drawId: number) {
  if (!UserId) {
    ElMessage.error('用户未授权')
    return 0
  }

  router.push({
    name: 'drawactRecord',
    query: {
      UserId,
      drawId,
    },
  })
}

const dialogFormVisible = ref(false)
// 提交表单
const submitForm = reactive({
  drawId: 0,
  sendNum: 0,
})

interface DrawactOption {
  drawId: number
  actStatus: number
}
const drawactOption = ref<DrawactOption[]>([])
function BatchSend() {
  submitForm.drawId = drawactOption.value[0].drawId
  submitForm.sendNum = 0
  dialogFormVisible.value = true
}

function SetSubmitForm() {
  // console.log(submitForm);
  if (!submitForm.sendNum) {
    ElMessage.error('请输入发送次数')
    return 0
  }
  submitForm.sendNum = toNumber(submitForm.sendNum)
  PostSendDrawChance(submitForm).then((dataRes: any) => {
    if (dataRes.succeeded) {
      ElMessage.success('发送成功')
      GetDataList()
      dialogFormVisible.value = false
    }
    else {
      if (typeof dataRes.errors === 'string') {
        ElMessage.error(`发送失败。${dataRes.errors}`)
      }
      else {
        let errorStr = ''
        for (const key in dataRes.errors) {
          errorStr += `${key}：${dataRes.errors[key]}；`
        }
        ElMessage.error(`发送失败。${errorStr}`)
      }
    }
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(async () => {
  if (localStorage.getItem('currentPage') !== null) {
    GetDataList(toNumber(localStorage.getItem('currentPage')), 20)
    localStorage.removeItem('currentPage')
  }
  else {
    GetDataList()
  }

  await GetOptionData().then((dataRes: any) => {
    if (dataRes.succeeded) {
      drawactOption.value = dataRes.data
    }
  })
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="抽奖活动ID">
                <el-input v-model="findFrom.DrawId" placeholder="请输入转盘活动ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="OpenId">
                <el-input v-model="findFrom.SCOpenId" placeholder="请输入OpenId" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="授权手机号">
                <el-input v-model="findFrom.UserPhone" placeholder="请输入授权手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="订单编号">
                <el-input v-model="findFrom.OrderNo" placeholder="请输入订单编号" clearable @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="BatchSend">
          批量发送
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="subscriberInfo.userId" label="用户ID" width="100" />
        <el-table-column align="center" prop="subscriberInfo.userNickName" label="用户信息" width="220">
          <template #default="scope">
            <div v-if="!scope.row.subscriberInfo">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriberInfo?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.subscriberInfo?.userNickName }}
                </p>
                <span>
                  {{ scope.row.subscriberInfo?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="subscriberInfo.scOpenId" label="用户OpenId" width="300" />
        <el-table-column align="center" prop="getNums" label="可抽奖次数" width="150" />
        <el-table-column align="center" prop="usedNums" label="已使用次数" width="150" />
        <el-table-column align="center" prop="drawId" label="活动ID" width="150" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="250" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="250" />
        <el-table-column align="center" label="操作" fixed="right" min-width="240">
          <template #default="scope">
            <el-button type="primary" @click="ViewDetails(scope.row.subscriberInfo?.userId, scope.row.drawId)">
              机会明细
            </el-button>
            <el-button type="primary" @click="GetDrawactRecord(scope.row.subscriberInfo?.userId, scope.row.drawId)">
              抽奖记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <el-dialog v-model="dialogFormVisible" title="批量发送抽奖次数" width="500">
      <el-form label-width="auto" :model="submitForm">
        <el-form-item label="抽奖活动" prop="drawId">
          <el-select v-model="submitForm.drawId" placeholder="请选择抽奖活动">
            <el-option v-for="item in drawactOption" :key="item.drawId" :label="item.drawId" :value="item.drawId" />
          </el-select>
        </el-form-item>
        <el-form-item label="发送抽奖次数" prop="sendNum">
          <el-input v-model="submitForm.sendNum" placeholder="请输入发送次数" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetSubmitForm">
            发送
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
